package logic

import (
	"context"
	"k8s.io/apimachinery/pkg/util/json"
	"shoppings/model/mysql"
	"shoppings/model/redis"
	"shoppings/shoprpc/internal/svc"
	"shoppings/shoprpc/shoprpc"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *shoprpc.ListRequest) (*shoprpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	name := in.Name
	var shop []mysql.Product
	get := redis.Rdb.Get("list" + strconv.Itoa(int(offset)) + name)
	if get.Val() == "" {
		tx := mysql.DB.Debug().Order("price desc").Offset(int(offset)).Limit(int(pageSize))
		if name != "" {
			tx.Where("name like ?", "%"+in.Name+"%").Find(&shop)
		}
		tx.Find(&shop)
		marshal, _ := json.Marshal(&shop)
		redis.Rdb.Set("list"+strconv.Itoa(int(offset))+name, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &shop)
	}
	var shops []*shoprpc.List
	for _, product := range shop {
		list := shoprpc.List{
			Number:   int64(product.Number),
			Image:    product.Image,
			Name:     product.Name,
			Nav:      product.Nav,
			Label:    product.Label,
			Price:    float32(product.Price),
			ActPrice: float32(product.ActPrice),
			Stock:    int64(product.Stock),
			Sales:    int64(product.Sales),
			Type:     product.Type,
			UserId:   int64(product.UserId),
			Id:       int64(product.ID),
		}
		shops = append(shops, &list)
	}
	return &shoprpc.ListResponse{List: shops}, nil
}
